import {
  createApp,
  reactive,
  toRefs,
  onMounted,
  onBeforeMount,
  nextTick,
  defineComponent,
} from "vue";
import Dict from "./Dict";
import { mergeOptions } from "./DictOptions";

function DataDict(app, options) {
  mergeOptions(options);

  app.mixin({
    setup() {
      const dict = reactive(new Dict());
      dict.owner = this;

      onBeforeMount(() => {
        if (!(dict instanceof Dict)) {
          return;
        }
        options.onCreated && options.onCreated(dict);
        dict.init(this.$options.dicts).then(() => {
          options.onReady && options.onReady(dict);
          nextTick(() => {
            this.$emit("dictReady", dict);
            if (
              this.$options.methods &&
              this.$options.methods.onDictReady instanceof Function
            ) {
              this.$options.methods.onDictReady.call(this, dict);
            }
          });
        });
      });
      return {
        ...toRefs(dict),
      };
    },
  });
}
export default DataDict;
